<template>
  <view class="container">
    <!-- 调试信息改为折叠面板，默认隐藏 -->
    <view class="debug-panel" v-if="false">
      <view class="debug-header" @click="showDebug = !showDebug">
        <text class="debug-title">调试信息</text>
        <text class="debug-icon">{{ showDebug ? '▼' : '▶' }}</text>
      </view>
      <view class="debug-content" v-if="showDebug">
        <text class="debug-text">{{ JSON.stringify({ 
          hasAccount: !!currentAccount, 
          accountInfo: currentAccount, 
          hasInfo: !!info,
          isWithinTimeRange: isWithinTimeRange()
        }, null, 2) }}</text>
      </view>
    </view>

  
    
    <!-- 账号信息面板 - 优化样式 -->
    <view class="account-info-panel" :class="{ 'no-account': !currentAccount }">
      <view class="account-info-content">
        <view class="account-display">
          <text class="account-nickname">{{ currentAccount ? (currentAccount.nickname || '未设置昵称') : '未登录' }}</text>
          <text class="account-id" v-if="currentAccount">修仙ID: {{ currentAccount.roleId }}</text>
          <text class="account-id" v-else>请先登录账号</text>
        </view>
        <button class="switch-account-btn" @click="navigateToAccountManager">
          <text class="button-icon">👤</text>
          {{ currentAccount ? '切换账号' : '去登录' }}
        </button>
      </view>
    </view>
    
    <!-- 控制面板 - 优化布局 -->
    <view class="control-panel" v-if="currentAccount">
      <view class="panel-header">
        <view class="button-group">
          <button class="control-button" 
            :class="{ 'button-primary': !isRunning, 'button-danger': isRunning }"
                  @click="isRunning ? stopPlunder(true) : startPlunder()">
            <text class="button-icon">{{ isRunning ? '⏹' : '▶' }}</text>
            {{ isRunning ? '停止' : '启动' }}
          </button>
          <button class="control-button button-secondary" @click="attackPrepare(0)">
            <text class="button-icon">🔍</text>
            查询
          </button>
          <button class="control-button button-secondary" @click="attackPrepare(1)">
            <text class="button-icon">🔄</text>
            刷新
          </button>
          <button class="control-button button-secondary" @click="navigateToConfig">
            <text class="button-icon">⚙️</text>
            设置
          </button>
        </view>
      </view>

      <!-- 状态信息 - 优化显示 -->
      <view class="status-info">
        <view class="status-item" :class="{ 'status-active': isRunning }">
          <text class="status-label">运行状态:</text>
          <text class="status-value">{{ status }}</text>
        </view>
        <view class="status-item">
          <text class="status-label">倒计时:</text>
          <text class="status-value">{{ countdown }}</text>
        </view>
        <view class="status-item" :class="{ 
            'status-active': isWithinTimeRange() && !manuallyStopped,
            'status-manual-stop': manuallyStopped 
          }">
          <text class="status-label">定时状态:</text>
          <text class="status-value">
            {{ manuallyStopped ? '手动停止' : (isWithinTimeRange() ? '运行时段内' : '运行时段外') }}
          </text>
        </view>
        <view class="status-item">
          <text class="status-label">当前时间:</text>
          <text class="status-value">{{ currentTime }}</text>
        </view>
      </view>
    </view>

    <!-- 角色列表 - 优化显示 -->
    <view class="role-list" v-if="currentAccount && info && info.roles && info.roles.length > 0">
      <view class="role-list-header">
        <text class="role-list-title">角色列表</text>
        <text class="role-list-count">共 {{ info.roles.length }} 个角色</text>
      </view>
      <view class="role-grid">
        <view v-for="(role, index) in info.roles" :key="index" 
              class="role-card" 
              :class="{ 'role-card-highlight': role.stone > config.threshold }">
          <view class="role-header">
            <text class="role-nickname">{{ role.nickname }}</text>
            <text class="role-stone" :class="{ 'highlight': role.stone > config.threshold }">
              {{ Math.floor(role.stone) }} 灵石
            </text>
          </view>
          <view class="role-info">
            <text class="role-level">{{ role.name }} {{ role.layer }}层</text>
            <text class="role-detail">等级: Lv.{{ role.level }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 提示信息 - 只在有内容时显示 -->
    <view class="tips" v-if="info && info.attackTips && info.attackTips.trim()">
      <text class="tips-icon">💡</text>
      <text class="tips-content">{{ info.attackTips }}</text>
    </view>
     <!-- 统计面板 - 优化显示 -->
     <stats-panel 
      v-if="currentAccount && plunderStats && typeof plunderStats === 'object'" 
      :stats="plunderStats" 
    />

    <!-- 日志面板 - 优化显示 -->
    <log-panel v-if="currentAccount && logs.length > 0" 
      :logs="logs"
      :scroll-to="scrollTo"
               @clear="clearLog" />

   
  </view>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';
import LogPanel from '@/components/LogPanel.vue';
import StatsPanel from '@/components/StatsPanel.vue';

// 将 debugLog 移到外部，使其成为全局函数
const debugLog = (message, data) => {
  console.log(`[DEBUG] ${message}`, data);
  // 只在关键操作时显示提示
  const showToastMessages = [
    'Token 已过期',
    '登录成功',
    '切换账号成功',
    '启动失败',
    '配置保存失败'
  ];
  
  if (showToastMessages.some(msg => message.includes(msg))) {
    uni.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });
  }
};

export default {
  components: {
    LogPanel,
    StatsPanel
  },
  setup(__props, { expose }) {
    // 添加时间格式化函数
    const formatTime = (date) => {
      if (!(date instanceof Date) || isNaN(date.getTime())) {
        // 如果输入不是有效的日期对象，尝试解析时间戳
        if (typeof date === 'string') {
          // 尝试从日志格式 [HH:mm:ss] 解析时间
          const timeMatch = date.match(/\[(\d{2}:\d{2}:\d{2})\]/);
          if (timeMatch) {
            return timeMatch[1];
          }
        }
        return '--:--:--';  // 返回默认值而不是 NaN
      }
      
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${hours}:${minutes}:${seconds}`;
    };

    // 添加记录时间格式化函数
    const formatRecordTime = (record) => {
      if (record.date) {
        // 如果有完整时间戳，使用它
        return formatTime(new Date(record.date));
      } else if (record.timestamp) {
        // 如果有格式化好的时间戳，直接使用
        return record.timestamp;
      }
      return '--:--:--';  // 默认值
    };

    // 常量定义
    const BASE_URL = 'https://farm-api.lucklyworld.com';
    const PREPARE_API = '/v8/api/game/bead/plunder/attack/prepare';
    const ATTACK_API = '/v8/api/game/bead/plunder/attack/start';
    const MAX_LOG_LINES = 1000;
    const MAX_RECORDS = 100;
    const RETRY_ATTEMPTS = 5;
    const LOG_CLEANUP_INTERVAL = 3600000; // 1小时清理一次
    const LOG_MAX_AGE = 3600000; // 日志保留1小时
    const RATE_LIMIT = {
      prepare: { maxRequests: 10, timeWindow: 60000 },
      attack: { maxRequests: 5, timeWindow: 60000 }
    };

    // 状态管理
    const isRunning = ref(false);
    const status = ref('已停止');
    const countdown = ref('N/A');
    const logs = ref([]);
    const scrollTo = ref('');
    const manuallyStopped = ref(false);
    const currentTime = ref('00:00:00');
    const info = ref({
      stone: { passive: '0', plunder: '0' },
      refresh: { used: 0, total: 0 },
      beadTray: 0,
      roles: [],
      attackTips: ''
    });
    const config = ref({
      nicknames: [],
      uid: '',
      roleId: '',
      token: '',
      threshold: '168.0',
      quickRefreshCount: '3',
      quickRefreshDuration: '40',
      quickRefreshInterval: '1',
      startTime: '10:00',
      stopTime: '11:40'
    });

    // 初始化 plunderStats 的函数
    const initPlunderStats = () => {
      const defaultStats = {
        totalAttempts: 0,
        successfulPlunders: 0,
        totalStones: 0.0,
        records: [],
        nicknameStats: {},
        beadTray: 0,
        refresh: { used: 0, total: 0 }
      };

      try {
        const accountId = currentAccount.value?.roleId;
        if (accountId) {
          const statsKey = `plunder_stats_${accountId}`;
          const savedStats = uni.getStorageSync(statsKey);
          plunderStats.value = savedStats || defaultStats;
        } else {
          plunderStats.value = defaultStats;
        }
      } catch (e) {
        console.error('初始化统计信息失败:', e);
        plunderStats.value = defaultStats;
      }
    };

    // 保存 plunderStats 的函数
    const savePlunderStats = () => {
      try {
        const accountId = currentAccount.value?.roleId;
        if (accountId && plunderStats.value) {
          const statsKey = `plunder_stats_${accountId}`;
          uni.setStorageSync(statsKey, plunderStats.value);
        }
      } catch (e) {
        console.error('保存统计信息失败:', e);
      }
    };

    const plunderStats = ref(null);
    initPlunderStats(); // 初始化 plunderStats

    // 监听账号变化，重新初始化统计信息
    watch(() => currentAccount.value?.roleId, (newRoleId) => {
      if (newRoleId) {
        initPlunderStats();
      } else {
        plunderStats.value = null;
      }
    });

    // 账号状态
    const currentAccount = ref(null);

    // 计算属性
    const successRate = computed(() => {
      return plunderStats.value.totalAttempts > 0
        ? ((plunderStats.value.successfulPlunders / plunderStats.value.totalAttempts) * 100).toFixed(2)
        : '0.00';
    });

    // 日志记录
    const log = (message) => {
      const timestamp = formatTime(new Date());
      const logEntry = `[${timestamp}] ${message}`;
      logs.value.unshift(logEntry);
      if (logs.value.length > MAX_LOG_LINES) {
        logs.value.pop();
      }
      scrollTo.value = logEntry;
      try {
        uni.setStorageSync('plunder_logs', logs.value);
      } catch (e) {
        console.error('保存日志失败:', e);
      }
    };

    // 清除日志
    const clearLog = () => {
      logs.value = [];
      scrollTo.value = '';
      try {
        uni.removeStorageSync('plunder_logs');
      } catch (e) {
        console.error('清除日志失败:', e);
      }
    };

    // 检查是否在运行时间段内
    const isWithinTimeRange = () => {
      try {
        const now = Date.now();
        // 如果距离上次检查时间不足5秒，直接返回缓存的结果
        if (now - lastTimeCheck.value < TIME_CHECK_INTERVAL) {
          return lastTimeCheckResult.value;
        }
        
        lastTimeCheck.value = now;
        
        if (manuallyStopped.value) {
          console.log('[时间检查] 手动停止状态');
          lastTimeCheckResult.value = false;
          return false;
        }
        
        const currentDate = new Date();
        const currentTime = currentDate.getHours() * 60 + currentDate.getMinutes();
        
        // 确保使用配置中的时间设置
        const startTimeStr = config.value.startTime;
        const stopTimeStr = config.value.stopTime;
        
        // 更严格的时间格式验证
        const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
        const isValidTime = (time) => {
          if (!time || typeof time !== 'string') return false;
          if (!timeRegex.test(time)) return false;
          const [hours, minutes] = time.split(':').map(Number);
          return hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59;
        };
        
        if (!isValidTime(startTimeStr) || !isValidTime(stopTimeStr)) {
          console.warn('[时间检查] 时间格式无效:', { startTimeStr, stopTimeStr });
          loadConfig();
          lastTimeCheckResult.value = false;
          return false;
        }
        
        const [startHour, startMinute] = startTimeStr.split(':').map(Number);
        const [stopHour, stopMinute] = stopTimeStr.split(':').map(Number);
        
        const startTime = startHour * 60 + startMinute;
        const stopTime = stopHour * 60 + stopMinute;
        
        // 处理跨天情况
        const isWithin = startTime <= stopTime
          ? currentTime >= startTime && currentTime < stopTime
          : currentTime >= startTime || currentTime < stopTime;
        
        // 只在状态发生变化时记录日志并更新缓存
        if (isWithin !== lastTimeCheckResult.value) {
          console.log('[时间检查] 状态变化:', {
            currentTime: `${currentDate.getHours()}:${currentDate.getMinutes()}`,
            startTime: startTimeStr,
            stopTime: stopTimeStr,
            isWithin,
            oldState: lastTimeCheckResult.value
          });
          lastTimeCheckResult.value = isWithin;
          
          // 如果状态变化，同步更新运行状态
          if (isRunning.value !== isWithin) {
            if (!isWithin) {
              console.log('[时间检查] 当前不在运行时间段内，停止运行');
              stopPlunder();
            } else if (!manuallyStopped.value) {
              console.log('[时间检查] 当前在运行时间段内，可以启动');
              // 不自动启动，等待用户手动启动
            }
          }
        }
        
        return isWithin;
      } catch (e) {
        console.error('[时间检查] 出错:', e);
        lastTimeCheckResult.value = false;
        return false;
      }
    };

    // 倒计时到下一个五分钟
    const secondsToNextFiveMinute = () => {
      const now = new Date();
      const minutes = now.getMinutes();
      const seconds = now.getSeconds();
      const nextFiveMinute = Math.ceil(minutes / 5) * 5;
      const diffMinutes = nextFiveMinute - minutes;
      const totalSeconds = diffMinutes * 60 - seconds;
      countdown.value = `${Math.floor(totalSeconds / 60)}:${(totalSeconds % 60).toString().padStart(2, '0')}`;
    };

    // 清理日志
    const cleanupLogs = () => {
      try {
        const now = new Date();
        logs.value = logs.value.filter(log => {
          const timestamp = log.match(/\[(.*?)\]/)?.[1];
          if (!timestamp) return true;
          
          // 使用当前年份解析时间戳
          const currentYear = now.getFullYear();
          const logTime = new Date(`${currentYear} ${timestamp}`).getTime();
          
          // 如果解析失败或时间戳无效，保留日志
          if (isNaN(logTime)) return true;
          
          return now.getTime() - logTime < LOG_MAX_AGE;
        });
        
        // 保存清理后的日志
        uni.setStorageSync('plunder_logs', logs.value);
      } catch (e) {
        console.error('清理日志失败:', e);
      }
    };

    // 更新统计
    const updateStats = (nickname, stones, targetRoleId, refresh) => {
      try {
        const now = new Date();
        const timestamp = formatTime(now);
        const record = {
          timestamp,
          nickname,
          targetRoleId,
          stones,
          date: now.getTime(),
          refresh: refresh || { used: 0, total: 0 }
        };
        
        // 确保 plunderStats 已初始化
        if (!plunderStats.value) {
          initPlunderStats();
        }
        
        // 更新记录
        plunderStats.value.records.unshift(record);
        if (plunderStats.value.records.length > MAX_RECORDS) {
          plunderStats.value.records.pop();
        }
        
        // 更新昵称统计
        if (!plunderStats.value.nicknameStats[nickname]) {
          plunderStats.value.nicknameStats[nickname] = { count: 0, stones: 0 };
        }
        plunderStats.value.nicknameStats[nickname].count++;
        plunderStats.value.nicknameStats[nickname].stones += stones;
        
        // 更新总统计
        plunderStats.value.totalAttempts++;
        plunderStats.value.successfulPlunders++;
        plunderStats.value.totalStones += stones;
        
        // 保存统计信息
        const account = currentAccount.value;
        if (account?.roleId) {
          const statsKey = `plunder_stats_${account.roleId}`;
          uni.setStorageSync(statsKey, plunderStats.value);
        }
      } catch (e) {
        console.error('更新统计信息失败:', e);
      }
    };

    // 查询灵珠
    const attackPrepare = async (isRefresh) => {
      const token = config.value.token || '';
      if (!token) {
        log('错误: Token 为空');
        status.value = 'Token 未设置';
        return null;
      }

      // 验证 token 格式
      if (!token.includes('.')) {
        log('Token 格式错误，请确保复制完整的 Token');
        status.value = 'Token 格式错误';
        return null;
      }

      const headers = {
        'User-Agent': 'com.caike.lomo/4.2.6 (Linux; U; Android 12; zh-cn) (91416; 402060)bbcbce6e97449754',
        'Channel': 'official',
        'ANDROIDID': 'a7b19730952f1068',
        'IMEI': '352746026192015',
        'test-encrypt': '0',
        'token': token,
        'Content-Type': 'application/json; charset=utf-8'
      };

      const requestData = {
        roleId: config.value.roleId,
        isRefresh: isRefresh ? 1 : 0,
        trayType: 0
      };

      // 验证 roleId
      if (!requestData.roleId) {
        log('错误: Role ID 为空');
        status.value = 'Role ID 未设置';
        return null;
      }

      for (let attempt = 0; attempt < RETRY_ATTEMPTS; attempt++) {
        try {
          status.value = `查询灵珠 (尝试 ${attempt + 1}/${RETRY_ATTEMPTS})...`;
          const response = await uni.request({
            url: `${BASE_URL}${PREPARE_API}?uid=${config.value.uid}&version=2.0.0`,
            method: 'POST',
            header: headers,
            data: requestData,
            timeout: 30000,  // 增加超时时间到30秒
            enableHttp2: true,  // 启用 HTTP/2
            enableQuic: true,   // 启用 QUIC
            enableCache: false  // 禁用缓存
          });

          if (response.statusCode === 200) {
            const data = response.data;
            if (!data) {
              throw new Error('Empty response data');
            }

            // 检查 token 是否过期
            if (data.code === 401 || (data.message && data.message.includes('token'))) {
              log('Token 已过期，请重新设置');
              status.value = 'Token 已过期';
              uni.showToast({
                title: 'Token 已过期，请重新设置',
                icon: 'none',
                duration: 2000
              });
              return null;
            }

            info.value = {
              stone: data.stone || { passive: '0', plunder: '0' },
              refresh: data.refreshNum || { used: 0, total: 0 },
              beadTray: data.beadTray || 0,  // 添加盘子数量
              roles: data.roleList || [],
              attackTips: data.attackTips || ''
            };

            // 同时更新统计面板的盘子信息
            if (data.beadTray !== undefined) {
              if (!plunderStats.value) {
                initPlunderStats();
              }
              plunderStats.value.beadTray = data.beadTray;
              savePlunderStats();
            }

            return data;
          } else if (response.statusCode === 400) {
            const errorMessage = response.data?.message || '未知错误';
            // 特殊处理"当前非战斗时间段"
            if (errorMessage.includes('当前非战斗时间段')) {
              return {
                statusCode: 400,
                data: response.data,
                isNonCombatTime: true  // 添加标记
              };
            }
            // 其他 400 错误
            return {
              statusCode: 400,
              data: response.data
            };
          } else if (response.statusCode === 401) {
            log('Token 已过期，请重新设置');
            status.value = 'Token 已过期';
            uni.showToast({
              title: 'Token 已过期，请重新设置',
              icon: 'none',
              duration: 2000
            });
            return null;
          } else {
            log(`请求失败 (${response.statusCode}): ${response.data?.message || '未知错误'}`);
            throw new Error(`HTTP ${response.statusCode}`);
          }
        } catch (e) {
          console.error('请求失败:', e);
          const errorMessage = e.message || '未知错误';
          
          // 处理超时错误
          if (errorMessage.includes('timeout') || errorMessage.includes('abort')) {
            log(`请求超时 (尝试 ${attempt + 1}/${RETRY_ATTEMPTS})，等待重试...`);
            status.value = `请求超时，等待重试 (${attempt + 1}/${RETRY_ATTEMPTS})`;
            // 超时后等待时间递增
            await new Promise(resolve => setTimeout(resolve, 2000 * (attempt + 1)));
            continue;
          }
          
          // 处理网络错误
          if (errorMessage.includes('network') || errorMessage.includes('fail')) {
            log(`网络错误 (尝试 ${attempt + 1}/${RETRY_ATTEMPTS})，等待重试...`);
            status.value = `网络错误，等待重试 (${attempt + 1}/${RETRY_ATTEMPTS})`;
            await new Promise(resolve => setTimeout(resolve, 3000 * (attempt + 1)));
            continue;
          }
          
          if (attempt === RETRY_ATTEMPTS - 1) {
            log(`查询失败: ${errorMessage}`);
            throw e;
          }
          
          // 其他错误等待后重试
          await new Promise(resolve => setTimeout(resolve, 2000 * (attempt + 1)));
        }
      }
      return null;
    };

    // 执行抢夺
    const executePlunder = async (targetRoleId, nickname) => {
      const headers = {
        'User-Agent': 'com.caike.lomo/4.2.6 (Linux; U; Android 12; zh-cn) (91416; 402060)bbcbce6e97449754',
        'Channel': 'official',
        'ANDROIDID': 'a7b19730952f1068',
        'IMEI': '352746026192015',
        'test-encrypt': '0',
        'token': config.value.token,
        'Content-Type': 'application/json; charset=utf-8'
      };

      const payload = {
        roleId: config.value.roleId,
        dRoleId: targetRoleId,
        trayType: 0
      };

      for (let attempt = 0; attempt < RETRY_ATTEMPTS; attempt++) {
        try {
          status.value = `抢夺 ${nickname} (尝试 ${attempt + 1}/${RETRY_ATTEMPTS})...`;
          const response = await uni.request({
            url: `${BASE_URL}${ATTACK_API}?uid=${config.value.uid}&version=2.0.0`,
            method: 'POST',
            header: headers,
            data: payload,
            timeout: 30000,  // 增加超时时间到30秒
            enableHttp2: true,  // 启用 HTTP/2
            enableQuic: true,   // 启用 QUIC
            enableCache: false  // 禁用缓存
          });
          
          // 更新总尝试次数
          if (!plunderStats.value) {
            initPlunderStats();
          }
          plunderStats.value.totalAttempts++;
          
          if (response.statusCode === 200) {
            const result = response.data;
            if (result.plunderResult?.status === 1) {
              const stones = parseFloat(result.plunderResult.stone);
              
              log(`抢夺成功，昵称: ${nickname}, 获得灵石: ${stones}`);
              status.value = `抢夺成功: ${nickname}, ${stones} 灵石`;
              updateStats(nickname, stones, targetRoleId, info.value.refresh);
              savePlunderStats();
              return result;
            } else {
              log(`抢夺失败，昵称: ${nickname}`);
              status.value = `抢夺失败: ${nickname}`;
            }
            return result;
          } else if (response.statusCode === 429) {
            log('请求过于频繁，暂停 30 秒');
            status.value = '请求限流，暂停 30 秒';
            await new Promise(resolve => setTimeout(resolve, 30000));
            continue;
          } else {
            log(`抢夺失败，昵称: ${nickname}, 状态码: ${response.statusCode}`);
            status.value = `抢夺失败: ${nickname}, 状态码 ${response.statusCode}`;
            return null;
          }
        } catch (e) {
          console.error('抢夺失败:', e);
          const errorMessage = e.message || '未知错误';
          
          // 处理超时错误
          if (errorMessage.includes('timeout') || errorMessage.includes('abort')) {
            log(`抢夺超时 (尝试 ${attempt + 1}/${RETRY_ATTEMPTS})，等待重试...`);
            status.value = `抢夺超时，等待重试 (${attempt + 1}/${RETRY_ATTEMPTS})`;
            await new Promise(resolve => setTimeout(resolve, 2000 * (attempt + 1)));
            continue;
          }
          
          // 处理网络错误
          if (errorMessage.includes('network') || errorMessage.includes('fail')) {
            log(`网络错误 (尝试 ${attempt + 1}/${RETRY_ATTEMPTS})，等待重试...`);
            status.value = `网络错误，等待重试 (${attempt + 1}/${RETRY_ATTEMPTS})`;
            await new Promise(resolve => setTimeout(resolve, 3000 * (attempt + 1)));
            continue;
          }
          
          log(`抢夺出错: ${errorMessage}`);
          await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
        }
      }
      log('达到最大重试次数，抢夺失败');
      status.value = '抢夺失败，达到最大重试次数';
      return null;
    };

    // 在 setup 函数开始处添加锁变量
    const isOperationLocked = ref(false);
    const operationLockTimeout = 15000; // 增加到15秒
    const lockRetryInterval = 2000; // 锁重试间隔2秒
    const maxLockRetries = 3; // 最大重试次数

    // 添加获取锁和释放锁的函数
    const acquireLock = async (operation = '未知操作') => {
      let retryCount = 0;
      const startTime = Date.now();
      
      while (retryCount < CONSTANTS.MAX_LOCK_RETRIES) {
        if (!isOperationLocked.value) {
          isOperationLocked.value = true;
          
          // 设置超时自动释放
          const timeoutId = setTimeout(() => {
            if (isOperationLocked.value) {
              log(`[锁] ${operation} 操作锁超时，自动释放`);
              isOperationLocked.value = false;
            }
          }, CONSTANTS.LOCK_TIMEOUT);
          
          // 保存超时ID
          uni.setStorageSync('lock_timeout_id', timeoutId);
          return true;
        }
        
        // 检查是否已经等待太长时间
        if (Date.now() - startTime > CONSTANTS.QUICK_CHECK_TIMEOUT) {
          log(`[锁] ${operation} 等待超时，放弃获取锁`);
          return false;
        }
        
        retryCount++;
        log(`[锁] ${operation} 等待锁释放 (${retryCount}/${CONSTANTS.MAX_LOCK_RETRIES})...`);
        await new Promise(resolve => setTimeout(resolve, CONSTANTS.LOCK_RETRY_INTERVAL));
      }
      
      log(`[锁] ${operation} 获取锁失败，达到最大重试次数`);
      return false;
    };

    // 修改 releaseLock 函数
    const releaseLock = (operation = '未知操作') => {
      if (isOperationLocked.value) {
        // 清除超时定时器
        try {
          const timeoutId = uni.getStorageSync('lock_timeout_id');
          if (timeoutId) {
            clearTimeout(timeoutId);
            uni.removeStorageSync('lock_timeout_id');
          }
        } catch (e) {
          console.error('清除锁超时定时器失败:', e);
        }
       
        isOperationLocked.value = false;
      }
    };

    // 添加角色昵称标准化函数
    const normalizeNickname = (nickname) => {
      if (!nickname) return '';
      return nickname.toLowerCase()
        .replace(/[&＆]/g, '&')
        .replace(/[《》]/g, '')
        .replace(/\s+/g, '')
        .trim();
    };

    // 在 setup 函数开始处添加常量定义
    const CONSTANTS = {
      CYCLE_INTERVAL: 3000, // 增加主循环间隔到3秒
      LOCK_TIMEOUT: 5000,   // 减少锁超时时间到8秒
      LOCK_RETRY_INTERVAL: 1000, // 减少锁重试间隔到1秒
      MAX_LOCK_RETRIES: 2,  // 减少最大重试次数到2次
      QUICK_CHECK_INTERVAL: 0.8, // 设置基础间隔为0.8秒
      QUICK_CHECK_RANDOM_DELAY: 0.05, // 减小随机延迟范围
      QUICK_CHECK_TIMEOUT: 5000 // 快速检测单次超时时间
    };

    // 修改 quickRefreshLoop 函数中的锁处理部分
    const quickRefreshLoop = async (targetRole, quickStartTime, quickRefreshDuration) => {
      let lastCheckTime = quickStartTime;
      // 直接使用配置值，不添加额外延迟
      const interval = parseFloat(config.value.quickRefreshInterval) || 4;
      let shouldBreak = false;
      let notFoundCount = 0;
      const maxNotFoundRetries = 3;
      const retryDelay = 2000;
      let consecutiveErrors = 0;
      const maxConsecutiveErrors = 3;

      while (Date.now() - quickStartTime < quickRefreshDuration * 1000 && isRunning.value && !shouldBreak) {
        const currentTime = Date.now();
        const timeSinceLastCheck = (currentTime - lastCheckTime) / 1000;

        // 直接使用配置的间隔值，不添加随机延迟
        if (timeSinceLastCheck < interval) {
          const waitTime = Math.max(100, (interval - timeSinceLastCheck) * 1000);
          await new Promise(resolve => setTimeout(resolve, waitTime));
          continue;
        }

        try {
          // 尝试获取锁，如果失败则跳过本次检测
          if (!await acquireLock('快速检测')) {
            log('快速检测等待超时，跳过本次检测');
            await new Promise(resolve => setTimeout(resolve, 1000));
            continue;
          }

          try {
            // 所有检测都使用查询
            const response = await attackPrepare(0);
            consecutiveErrors = 0;

            if (!response) {
              log('快速检测失败，等待重试');
              status.value = `快速检测: ${targetRole.nickname} (失败重试)`;
              return false;
            }

            if (response.error === 'refresh_exhausted') {
              log(`快速检测中刷新次数已用尽，继续等待目标角色: ${targetRole.nickname}`);
              status.value = `快速检测: ${targetRole.nickname} (刷新次数用尽)`;
              await new Promise(resolve => setTimeout(resolve, 2000));
              continue;
            }

            const roleList = response.roleList || [];
            let targetFound = false;
            const normalizedTargetNickname = normalizeNickname(targetRole.nickname);

            // 记录当前列表状态
            const topThreeRoles = roleList.slice(0, 3);
            const topThreeInfo = topThreeRoles.map(role => 
              `${role.nickname}(${Math.floor(role.stone)})`
            ).join('、');

            for (const role of roleList) {
              const currentNickname = normalizeNickname(role.nickname);
              if (currentNickname === normalizedTargetNickname) {
                targetFound = true;
                notFoundCount = 0;
                targetRole.stone = parseFloat(role.stone || 0);
                targetRole.roleId = role.roleId;
                log(`[目标] 找到目标: ${role.nickname} (${targetRole.stone.toFixed(2)})`);
                status.value = `快速检测: ${role.nickname} (${targetRole.stone.toFixed(2)})`;

                if (targetRole.stone > parseFloat(config.value.threshold)) {
                  log(`[抢夺] 灵石满足条件 (>${config.value.threshold})，准备抢夺`);
                  await executePlunder(targetRole.roleId, role.nickname);
                  log('[抢夺] 抢夺完成，退出快速检测');
                  status.value = '抢夺完成';
                  await new Promise(resolve => setTimeout(resolve, 2000 + Math.random() * 1000));
                  shouldBreak = true;
                }
                break;
              }
            }

            if (!targetFound) {
              notFoundCount++;
              log(`[目标] ${targetRole.nickname} 不在列表中 (${notFoundCount}/${maxNotFoundRetries})`);
              status.value = `目标 ${targetRole.nickname} 不在列表 (${notFoundCount}/${maxNotFoundRetries})`;

              if (notFoundCount >= maxNotFoundRetries) {
                log(`[目标] ${targetRole.nickname} 连续 ${maxNotFoundRetries} 次未找到，确认已离开列表`);
                status.value = `目标 ${targetRole.nickname} 确认离开`;
                shouldBreak = true;
              } else {
                log(`等待 ${retryDelay/1000} 秒后重试...`);
                await new Promise(resolve => setTimeout(resolve, retryDelay));
              }
            }

            lastCheckTime = currentTime;
          } finally {
            // 确保释放锁
            releaseLock('快速检测');
          }

        } catch (e) {
          console.error('快速检测出错:', e);
          consecutiveErrors++;
          releaseLock('快速检测-错误');
          
          if (consecutiveErrors >= maxConsecutiveErrors) {
            log(`[错误] 连续 ${maxConsecutiveErrors} 次检测出错，退出快速检测`);
            shouldBreak = true;
          } else {
            log(`[错误] 检测出错，等待重试 (${consecutiveErrors}/${maxConsecutiveErrors})`);
            await new Promise(resolve => setTimeout(resolve, 2000));
          }
        }
      }

      return shouldBreak;
    };

    // 添加循环锁变量
    let isCycleRunning = false;

    // 主循环
    const runCycle = async () => {
      if (!isRunning.value || isCycleRunning) return;
      
      try {
        isCycleRunning = true;
        log('[主循环] 开始自动抢夺灵珠');
        let cycleCount = 0;
        let firstCycle = true;
        let lastCycleTime = Date.now();
        const nicknameSet = new Set(config.value.nicknames.map(normalizeNickname));

        while (isRunning.value && isWithinTimeRange()) {
          try {
            const now = Date.now();
            const timeSinceLastCycle = now - lastCycleTime;

            if (timeSinceLastCycle < CONSTANTS.CYCLE_INTERVAL) {
              const waitTime = CONSTANTS.CYCLE_INTERVAL - timeSinceLastCycle;
              await new Promise(resolve => setTimeout(resolve, waitTime));
              continue;
            }

            // 尝试获取锁，如果失败则等待后继续
            if (!await acquireLock('主循环')) {
              log('[主循环] 获取锁失败，等待后重试');
              await new Promise(resolve => setTimeout(resolve, 1000));
              continue;
            }

            try {
              cycleCount++;
              log(`[主循环] 第 ${cycleCount} 次循环开始`);
              status.value = `循环 ${cycleCount} 开始`;
              lastCycleTime = Date.now();

              const isRefresh = firstCycle ? 0 : 1;
              const response = await attackPrepare(isRefresh);
              
              if (!response) {
                log('[主循环] 查询失败，等待重试');
                status.value = '查询失败，等待重试';
                await new Promise(resolve => setTimeout(resolve, 10000 + Math.random() * 2000));
                continue;
              }

              // 检查是否是 400 错误
              if (response.statusCode === 400) {
                // 特殊处理"当前非战斗时间段"
                if (response.isNonCombatTime) {
                  log('当前非战斗时间段，停止运行');
                  status.value = '已停止';
                  stopPlunder();
                  return;
                }
                
                // 其他 400 错误处理
                const errorMessage = response.data?.message || '未知错误';
                const errorCode = response.data?.code || '未知错误码';
                log(`遇到 400 错误: [${errorCode}] ${errorMessage}`);
                status.value = '已停止';  // 简化状态显示
                await new Promise(resolve => setTimeout(resolve, 5000));
                stopPlunder();
                await new Promise(resolve => setTimeout(resolve, 1000));
                startPlunder();
                return;
              }

              if (response.error === 'not_registered') {
                return;
              }

              if (response.error === 'refresh_exhausted') {
                const roleList = response.roleList || [];
                const maxStoneRole = roleList.reduce((max, role) => {
                  const stones = parseFloat(role.stone || 0);
                  return stones > parseFloat(max.stone || 0) ? role : max;
                }, { stone: 0 });

                if (maxStoneRole.roleId) {
                  log(`抢夺灵石最高的角色: ${maxStoneRole.nickname} (灵石: ${maxStoneRole.stone})`);
                  await executePlunder(maxStoneRole.roleId, maxStoneRole.nickname);
                  await new Promise(resolve => setTimeout(resolve, 3000 + Math.random() * 2000));
                } else {
                  log('无可用角色，等待10秒后重试');
                  status.value = '无可用角色，等待10秒';
                  await new Promise(resolve => setTimeout(resolve, 10000 + Math.random() * 2000));
                }
                continue;
              }

              firstCycle = false;
              const roleList = response.roleList || [];
              const refreshUsed = response.refreshNum?.used || 0;
              const refreshTotal = response.refreshNum?.total || 10;

              let targetRole = null;
              for (const role of roleList) {
                const nickname = normalizeNickname(role.nickname);
                if (nicknameSet.has(nickname)) {
                  targetRole = { 
                    roleId: role.roleId, 
                    nickname: role.nickname,
                    stone: parseFloat(role.stone || 0) 
                  };
                  log(`[目标] 找到名单中的角色: ${role.nickname}, 灵石: ${targetRole.stone}`);
                  status.value = `找到目标: ${role.nickname}, 灵石 ${targetRole.stone}`;
                  break;
                }
              }

              if (targetRole) {
                if (targetRole.stone > parseFloat(config.value.threshold)) {
                  log(`灵石满足条件 (>${config.value.threshold})，抢夺角色: ${targetRole.nickname}`);
                  await executePlunder(targetRole.roleId, targetRole.nickname);
                  log('抢夺完成，等待3秒后继续下一次循环');
                  status.value = '抢夺完成，等待3秒';
                  await new Promise(resolve => setTimeout(resolve, 3000 + Math.random() * 2000));
                } else {
                  // 灵石不足，执行快速刷新逻辑
                  log(`灵石不足 (<= ${config.value.threshold})，开始快速检测: ${targetRole.nickname}`);
                  status.value = `快速检测: ${targetRole.nickname}`;
                  
                  // 释放主循环的锁，让快速检测可以执行
                  releaseLock('主循环');
                  
                  let quickRefreshCount = 0;
                  const quickRefreshCountMax = parseInt(config.value.quickRefreshCount) || 3;
                  const quickRefreshDuration = parseInt(config.value.quickRefreshDuration) || 40;

                  while (quickRefreshCount < quickRefreshCountMax && isRunning.value) {
                    quickRefreshCount++;
                    log(`第 ${quickRefreshCount}/${quickRefreshCountMax} 次快速检测开始`);
                    
                    const quickStartTime = Date.now();
                    const shouldBreak = await quickRefreshLoop(targetRole, quickStartTime, quickRefreshDuration);

                    if (shouldBreak) {
                      log(`快速检测退出，原因: ${targetRole.stone > parseFloat(config.value.threshold) ? '灵石满足条件' : '目标不在列表'}`);
                      break;
                    }

                    if (quickRefreshCount < quickRefreshCountMax) {
                      const interval = parseFloat(config.value.quickRefreshInterval) || 4;
                      log(`等待 ${interval} 秒后开始下一次快速检测`);
                      await new Promise(resolve => setTimeout(resolve, interval * 1000));
                    }
                  }

                  // 快速检测完成后，重新获取主循环的锁
                  if (!await acquireLock('主循环')) {
                    log('[主循环] 快速检测后获取锁失败，等待后重试');
                    await new Promise(resolve => setTimeout(resolve, 1000));
                    continue;
                  }

                  if (quickRefreshCount === quickRefreshCountMax) {
                    log(`已完成 ${quickRefreshCountMax} 次快速检测，灵石仍不足，强制抢夺: ${targetRole.nickname}`);
                    status.value = `强制抢夺: ${targetRole.nickname}`;
                    await executePlunder(targetRole.roleId, targetRole.nickname);
                    await new Promise(resolve => setTimeout(resolve, 3000 + Math.random() * 2000));
                  }
                }
              } else {
                if (refreshUsed >= refreshTotal) {
                  // 如果已经找到了目标角色（即使灵石不足），继续等待
                  if (targetRole) {
                    log(`刷新次数已用尽，继续等待目标角色: ${targetRole.nickname}`);
                    status.value = `刷新次数用尽，等待目标: ${targetRole.nickname}`;
                    await new Promise(resolve => setTimeout(resolve, 2000 + Math.random() * 2000));
                  } else {
                    // 修改为选择等级最低的角色
                    const minLevelRole = roleList.reduce((min, role) => {
                      const level = parseInt(role.level || 0);
                      return level < parseInt(min.level || 999999) ? role : min;
                    }, { level: 999999 });

                    if (minLevelRole.roleId) {
                      log(`未找到目标角色，抢夺等级最低的角色: ${minLevelRole.nickname} (等级: ${minLevelRole.level})`);
                      await executePlunder(minLevelRole.roleId, minLevelRole.nickname);
                      await new Promise(resolve => setTimeout(resolve, 3000 + Math.random() * 2000));
                    } else {
                      log('无可用角色，等待10秒后重试');
                      status.value = '无可用角色，等待10秒';
                      await new Promise(resolve => setTimeout(resolve, 10000 + Math.random() * 2000));
                    }
                  }
                } else {
                  // 未找到目标且还有刷新次数，直接继续
                }
              }
            } finally {
              // 确保释放锁
              releaseLock('主循环');
            }

          } catch (e) {
            console.error('循环执行出错:', e);
            releaseLock('主循环-错误');
            const errorMessage = e.message || '未知错误';
            const errorDetails = e.response?.data || {};
            log(`循环执行出错: ${errorMessage}`);
            if (errorDetails.message) {
              log(`错误详情: ${JSON.stringify(errorDetails)}`);
            }
            status.value = '已停止';
            
            // 检查是否是 400 错误
            if (errorMessage.includes('400')) {
              // 特殊处理"当前非战斗时间段"
              if (errorMessage.includes('当前非战斗时间段') || 
                  (errorDetails.message && errorDetails.message.includes('当前非战斗时间段'))) {
                log('当前非战斗时间段，停止运行');
                status.value = '已停止';
                stopPlunder();
                return;
              }
              
              // 其他 400 错误处理
              const errorInfo = errorDetails.message || errorMessage;
              log(`遇到 400 错误: ${errorInfo}`);
              status.value = '已停止';  // 简化状态显示
              await new Promise(resolve => setTimeout(resolve, 5000));
              stopPlunder();
              await new Promise(resolve => setTimeout(resolve, 1000));
              startPlunder();
              return;
            }
            
            // 其他错误等待后继续
            await new Promise(resolve => setTimeout(resolve, 10000 + Math.random() * 2000));
          }
        }

        if (isRunning.value) {
          log('当前时间超出运行时间段，自动停止');
          isRunning.value = false;
          status.value = '已停止（定时）';
          countdown.value = 'N/A';
        }
      } finally {
        isCycleRunning = false;
        releaseLock('主循环-结束');
      }
    };

    // 添加后台运行相关代码
    const setupBackgroundMode = () => {
      // #ifdef APP-PLUS
      if (plus.os.name === 'Android') {
        try {
          // 申请后台运行权限
          plus.android.requestPermissions(
            ['android.permission.WAKE_LOCK'],
            function(resultObj) {
              if (resultObj.granted.length === 1) {
                try {
                  // 获取电源管理器
                  const powerManager = plus.android.importClass("android.os.PowerManager");
                  const mainActivity = plus.android.runtimeMainActivity();
                  const powerService = mainActivity.getSystemService("power");
                  const wakeLock = powerService.newWakeLock(
                    powerManager.PARTIAL_WAKE_LOCK,
                    "MyApp::PlunderWakeLock"
                  );
                  
                  // 确保 wakeLock 对象有效
                  if (wakeLock && typeof wakeLock.acquire === 'function') {
                    wakeLock.acquire();
                    // 保存 wakeLock 引用
                    uni.setStorageSync('wakeLock', JSON.stringify({
                      type: 'android_wake_lock',
                      timestamp: Date.now()
                    }));
                    log('已获取后台运行权限');
                  } else {
                    log('获取 wakeLock 对象失败');
                  }
                } catch (e) {
                  console.error('设置 wakeLock 失败:', e);
                  log('设置后台运行失败: ' + e.message);
                }
              } else {
                log('获取后台运行权限失败');
                uni.showToast({
                  title: '请授予后台运行权限',
                  icon: 'none'
                });
              }
            },
            function(error) {
              log('申请权限失败: ' + error.message);
            }
          );
        } catch (e) {
          console.error('设置后台运行失败:', e);
          log('设置后台运行失败: ' + e.message);
        }
      }
      // #endif
    };

    // 修改状态重置函数
    const resetRunningState = () => {
      isRunning.value = false;
      status.value = '已停止';
      countdown.value = 'N/A';
      // 不要在这里重置 manuallyStopped，因为它应该保持用户的手动停止状态
      try {
        uni.removeStorageSync('plunder_running');
        // 保存手动停止状态
        uni.setStorageSync('plunder_manually_stopped', manuallyStopped.value);
      } catch (e) {
        console.error('清除运行状态失败:', e);
      }
    };

    // 添加防抖函数
    const debounce = (fn, delay) => {
      let timer = null;
      return function (...args) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(this, args);
        }, delay);
      };
    };

    // 修改导航到配置页面的方法
    const navigateToConfig = debounce(() => {
      if (isRunning.value) {
        uni.showModal({
          title: '提示',
          content: '程序正在运行中，是否停止并进入设置？',
          success: (res) => {
            if (res.confirm) {
              stopPlunder(true); // 手动停止
              setTimeout(() => {
                uni.switchTab({
                  url: '/pages/attack/index'
                });
              }, 500);
            }
          }
        });
      } else {
        uni.switchTab({
          url: '/pages/attack/index'
        });
      }
    }, 300);

    // 修改导航到账号管理页面的方法
    const navigateToAccountManager = debounce(() => {
      if (isRunning.value) {
        uni.showModal({
          title: '提示',
          content: '程序正在运行中，是否停止并切换账号？',
          success: (res) => {
            if (res.confirm) {
              stopPlunder(true); // 手动停止
              setTimeout(() => {
                uni.switchTab({
                  url: '/pages/saoma/saoma'
                });
              }, 500);
            }
          }
        });
      } else {
        uni.switchTab({
          url: '/pages/saoma/saoma'
        });
      }
    }, 300);

    // 修改停止抢夺函数
    const stopPlunder = async (isManualStop = false) => {
      if (!isRunning.value) {
        return;
      }

      // 如果是手动停止，设置手动停止状态
      if (isManualStop) {
        manuallyStopped.value = true;
        debugLog('手动停止，设置手动停止状态');
        // 保存手动停止状态
        try {
          uni.setStorageSync('plunder_manually_stopped', true);
        } catch (e) {
          console.error('保存手动停止状态失败:', e);
        }
      }

      isRunning.value = false;  // 先设置停止标志
      isCycleRunning = false;   // 释放循环锁
      status.value = '已停止';
      debugLog('自动抢夺已停止');

      // 使用 Promise.all 确保所有通知都发送
      await Promise.all([
        new Promise(resolve => {
          uni.$emit('running-state-changed', { isRunning: false });
          resolve();
        }),
        new Promise(resolve => {
          uni.$emit('globalStateChange', { isRunning: false });
          resolve();
        })
      ]);
      debugLog('已通知其他页面运行状态已改变');

      // 清理运行状态
      try {
        uni.removeStorageSync('plunder_running');
      } catch (e) {
        console.error('清除运行状态失败:', e);
      }

      // #ifdef APP-PLUS
      try {
        const wakeLockInfo = uni.getStorageSync('wakeLock');
        if (wakeLockInfo) {
          const wakeLockData = JSON.parse(wakeLockInfo);
          if (wakeLockData.type === 'android_wake_lock') {
            // 获取电源管理器
            const powerManager = plus.android.importClass("android.os.PowerManager");
            const mainActivity = plus.android.runtimeMainActivity();
            const powerService = mainActivity.getSystemService("power");
            const wakeLock = powerService.newWakeLock(
              powerManager.PARTIAL_WAKE_LOCK,
              "MyApp::PlunderWakeLock"
            );
            
            if (wakeLock && typeof wakeLock.release === 'function') {
              wakeLock.release();
              uni.removeStorageSync('wakeLock');
              debugLog('已释放后台运行权限');
            }
          }
        }
      } catch (e) {
        console.error('释放 wakeLock 失败:', e);
        debugLog('释放后台运行权限失败: ' + e.message);
      }
      // #endif
    };

    // 修改开始抢夺函数
    const startPlunder = async () => {
      // 检查手动停止状态
      const wasManuallyStopped = uni.getStorageSync('plunder_manually_stopped') || false;
      if (wasManuallyStopped) {
        debugLog('当前处于手动停止状态，需要手动启动');
        uni.showModal({
          title: '提示',
          content: '当前处于手动停止状态，是否重新启动？',
          success: (res) => {
            if (res.confirm) {
              manuallyStopped.value = false;
              uni.setStorageSync('plunder_manually_stopped', false);
              startPlunderInternal();
            }
          }
        });
        return;
      }

      await startPlunderInternal();
    };

    // 内部启动函数
    const startPlunderInternal = async () => {
      if (isRunning.value) {
        debugLog('已经在运行中，重置状态后重试');
        resetRunningState();
        await new Promise(resolve => setTimeout(resolve, 1000));
      }

      // 检查是否已有循环在运行
      if (isCycleRunning) {
        debugLog('已有循环在运行中，不重复启动');
        return;
      }

      if (!isWithinTimeRange()) {
        debugLog('当前不在运行时间段内');
        return;
      }

      const savedConfig = uni.getStorageSync('plunder_config');
      if (!savedConfig) {
        debugLog('未找到配置信息，请先进行设置');
        uni.showToast({ title: '请先进行设置', icon: 'none' });
        navigateToConfig();
        return;
      }

      if (!savedConfig.token) {
        debugLog('Token 未设置，请先设置 Token');
        uni.showToast({ title: '请先设置 Token', icon: 'none' });
        navigateToConfig();
        return;
      }

      if (!savedConfig.roleId) {
        debugLog('Role ID 未设置');
        uni.showToast({ title: '请先设置 Role ID', icon: 'none' });
        navigateToConfig();
        return;
      }

      if (!savedConfig.nicknames?.length) {
        debugLog('目标昵称列表为空');
        uni.showToast({ title: '请先设置目标昵称', icon: 'none' });
        navigateToConfig();
        return;
      }

      try {
        config.value = savedConfig;
        isRunning.value = true;
        status.value = '正在启动...';
        debugLog('开始运行抢夺程序');

        // 保存运行状态并通知其他页面
        try {
          uni.setStorageSync('plunder_running', true);
          // 使用 Promise.all 确保所有通知都发送
          await Promise.all([
            new Promise(resolve => {
              uni.$emit('running-state-changed', { isRunning: true });
              resolve();
            }),
            new Promise(resolve => {
              uni.$emit('globalStateChange', { isRunning: true });
              resolve();
            })
          ]);
          debugLog('已通知其他页面运行状态已改变');
        } catch (e) {
          console.error('保存运行状态失败:', e);
        }

        // 设置后台运行
        setupBackgroundMode();

        // 开始运行循环
        await runCycle();
      } catch (e) {
        console.error('启动失败:', e);
        debugLog('启动失败: ' + e.message);
        status.value = '启动失败';
        resetRunningState();
        // 通知其他页面运行状态已改变
        await Promise.all([
          new Promise(resolve => {
            uni.$emit('running-state-changed', { isRunning: false });
            resolve();
          }),
          new Promise(resolve => {
            uni.$emit('globalStateChange', { isRunning: false });
            resolve();
          })
        ]);
      }
    };

    // 修改 loadConfig 函数
    const loadConfig = () => {
      try {
            console.log('开始加载配置...');
        const savedConfig = uni.getStorageSync('plunder_config');
            console.log('读取到的配置:', savedConfig);
            
        if (savedConfig) {
              // 验证时间格式
              const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
              const isValidTime = (time) => timeRegex.test(time);
              
              // 获取当前时间
              const now = new Date();
              const currentHour = now.getHours();
              const currentMinute = now.getMinutes();
              
              // 设置默认时间范围
              let defaultStartTime = '10:00';
              let defaultStopTime = '11:45';
              
              if (currentHour >= 11) {
                // 如果当前时间已经过了11点45分，设置明天的时间范围
                defaultStartTime = '10:00';
                defaultStopTime = '11:45';
              } else if (currentHour < 10) {
                // 如果当前时间在10点前，设置今天的时间范围
                defaultStartTime = '10:00';
                defaultStopTime = '11:45';
              } else {
                // 如果当前时间在10点到11点45分之间，设置剩余时间范围
                defaultStartTime = `${currentHour}:${currentMinute.toString().padStart(2, '0')}`;
                defaultStopTime = '11:45';
              }
              
              // 更新配置，确保时间格式正确
          config.value = {
            nicknames: Array.isArray(savedConfig.nicknames) ? savedConfig.nicknames : [],
            uid: savedConfig.uid || '',
            roleId: String(savedConfig.roleId || ''),
            token: savedConfig.token?.trim() || '',
            threshold: String(savedConfig.threshold || '168.0'),
            quickRefreshCount: String(savedConfig.quickRefreshCount || '3'),
            quickRefreshDuration: String(savedConfig.quickRefreshDuration || '40'),
            quickRefreshInterval: String(savedConfig.quickRefreshInterval || '4'),
                startTime: isValidTime(savedConfig.startTime) ? savedConfig.startTime : defaultStartTime,
                stopTime: isValidTime(savedConfig.stopTime) ? savedConfig.stopTime : defaultStopTime
          };
          
              // 如果时间格式无效，保存更新后的配置
              if (!isValidTime(savedConfig.startTime) || !isValidTime(savedConfig.stopTime)) {
                console.log('时间格式无效，更新配置为:', {
                  startTime: config.value.startTime,
                  stopTime: config.value.stopTime
                });
                uni.setStorageSync('plunder_config', config.value);
          }
          
          console.log('加载的配置:', {
            startTime: config.value.startTime,
            stopTime: config.value.stopTime
          });
            } else {
              console.log('未找到保存的配置，使用默认值');
              // 使用默认配置
              config.value = {
                nicknames: [],
                uid: '',
                roleId: '',
                token: '',
                threshold: '168.0',
                quickRefreshCount: '3',
                quickRefreshDuration: '40',
                quickRefreshInterval: '4',
                startTime: defaultStartTime,
                stopTime: defaultStopTime
              };
              // 保存默认配置
              uni.setStorageSync('plunder_config', config.value);
        }
      } catch (e) {
        console.error('加载配置失败:', e);
            // 使用默认配置
            config.value = {
              nicknames: [],
              uid: '',
              roleId: '',
              token: '',
              threshold: '168.0',
              quickRefreshCount: '3',
              quickRefreshDuration: '60',
              quickRefreshInterval: '1',
              startTime: '10:00',
              stopTime: '11:40'
            };
          }
    };

    // 修改配置更新函数
    const updateConfig = (newConfig) => {
      try {
        console.log('开始更新配置...');
        
        // 验证时间格式
        if (newConfig.startTime && !isValidTimeFormat(newConfig.startTime)) {
          console.warn('开始时间格式无效，使用默认值');
          newConfig.startTime = '10:00';
        }
        if (newConfig.stopTime && !isValidTimeFormat(newConfig.stopTime)) {
          console.warn('结束时间格式无效，使用默认值');
          newConfig.stopTime = '11:45';
        }
        
        // 更新配置
        config.value = {
          ...config.value,
          ...newConfig,
          startTime: newConfig.startTime || config.value.startTime || '10:00',
          stopTime: newConfig.stopTime || config.value.stopTime || '11:45'
        };
        
        // 保存配置
        saveConfig();
        
        console.log('配置已更新:', {
          startTime: config.value.startTime,
          stopTime: config.value.stopTime
        });
        
        // 如果正在运行，检查是否需要停止
        if (isRunning.value && !isWithinTimeRange()) {
          log('当前时间不在运行时段内，自动停止');
          stopPlunder();
        }
      } catch (e) {
        console.error('更新配置失败:', e);
        log('更新配置失败: ' + e.message);
      }
    };

    // 修改保存配置函数
    const saveConfig = () => {
      try {
        const configToSave = {
          ...config.value,
          token: config.value.token?.trim() || '',
          startTime: config.value.startTime || '10:00',
          stopTime: config.value.stopTime || '11:45'
        };
        
        console.log('保存配置:', {
          startTime: configToSave.startTime,
          stopTime: configToSave.stopTime
        });
        
        uni.setStorageSync('plunder_config', configToSave);
      } catch (e) {
        console.error('保存配置失败:', e);
        log('保存配置失败: ' + e.message);
      }
    };

        // 修改 loadCurrentAccount 函数
        const loadCurrentAccount = async () => {
          try {
            debugLog('开始加载当前账号信息');
            const currentAccountId = uni.getStorageSync('current_account_id');
            const accounts = uni.getStorageSync('plunder_accounts') || [];
            debugLog('当前账号ID', currentAccountId);
            debugLog('所有账号列表', accounts);
            
            if (currentAccountId) {
              const account = accounts.find(acc => acc.roleId === currentAccountId);
              if (account) {
                debugLog('找到当前账号', account);
                currentAccount.value = account;
                
                // 加载该账号的统计信息
                try {
                  const statsKey = `plunder_stats_${account.roleId}`;
                  const savedStats = uni.getStorageSync(statsKey);
                  if (savedStats) {
                    // 确保所有必要的字段都存在
                    plunderStats.value = {
                      totalAttempts: savedStats.totalAttempts || 0,
                      successfulPlunders: savedStats.successfulPlunders || 0,
                      totalStones: savedStats.totalStones || 0.0,
                      records: savedStats.records || [],
                      nicknameStats: savedStats.nicknameStats || {},
                      beadTray: savedStats.beadTray || 0,
                      refresh: savedStats.refresh || { used: 0, total: 0 }
                    };
                    console.log('已加载统计信息:', statsKey, plunderStats.value);
                  } else {
                    // 如果没有保存的统计信息，初始化新的统计对象
                    plunderStats.value = {
                      totalAttempts: 0,
                      successfulPlunders: 0,
                      totalStones: 0.0,
                      records: [],
                      nicknameStats: {},
                      beadTray: 0,
                      refresh: { used: 0, total: 0 }
                    };
                    // 保存初始化的统计信息
                    uni.setStorageSync(statsKey, plunderStats.value);
                    console.log('初始化新的统计信息');
                  }
                } catch (e) {
                  console.error('加载统计信息失败:', e);
                  // 确保 plunderStats 有初始值
                  plunderStats.value = {
                    totalAttempts: 0,
                    successfulPlunders: 0,
                    totalStones: 0.0,
                    records: [],
                    nicknameStats: {},
                    beadTray: 0,
                    refresh: { used: 0, total: 0 }
                  };
                }
                
                // 同步更新配置
                const existingConfig = uni.getStorageSync('plunder_config') || {};
                const configToSave = {
                  ...existingConfig,
                  token: account.token,
                  uid: account.uid,
                  roleId: account.roleId,
                  nickname: account.nickname
                };
                uni.setStorageSync('plunder_config', configToSave);
                config.value = configToSave;
                
                debugLog('已更新配置', configToSave);
              } else {
                debugLog('未找到对应的账号信息');
                currentAccount.value = null;
                // 重置统计信息
                plunderStats.value = {
                  totalAttempts: 0,
                  successfulPlunders: 0,
                  totalStones: 0.0,
                  records: [],
                  nicknameStats: {},
                  beadTray: 0,
                  refresh: { used: 0, total: 0 }
                };
              }
            } else if (accounts.length > 0) {
              debugLog('使用第一个账号作为当前账号', accounts[0]);
              currentAccount.value = accounts[0];
              uni.setStorageSync('current_account_id', accounts[0].roleId);
              
              // 加载该账号的统计信息
              try {
                const statsKey = `plunder_stats_${accounts[0].roleId}`;
                const savedStats = uni.getStorageSync(statsKey);
                if (savedStats) {
                  plunderStats.value = {
                    totalAttempts: savedStats.totalAttempts || 0,
                    successfulPlunders: savedStats.successfulPlunders || 0,
                    totalStones: savedStats.totalStones || 0.0,
                    records: savedStats.records || [],
                    nicknameStats: savedStats.nicknameStats || {},
                    beadTray: savedStats.beadTray || 0,
                    refresh: savedStats.refresh || { used: 0, total: 0 }
                  };
                } else {
                  plunderStats.value = {
                    totalAttempts: 0,
                    successfulPlunders: 0,
                    totalStones: 0.0,
                    records: [],
                    nicknameStats: {},
                    beadTray: 0,
                    refresh: { used: 0, total: 0 }
                  };
                  uni.setStorageSync(statsKey, plunderStats.value);
                }
              } catch (e) {
                console.error('加载统计信息失败:', e);
                plunderStats.value = {
                  totalAttempts: 0,
                  successfulPlunders: 0,
                  totalStones: 0.0,
                  records: [],
                  nicknameStats: {},
                  beadTray: 0,
                  refresh: { used: 0, total: 0 }
                };
              }
              
              // 同步更新配置
              const existingConfig = uni.getStorageSync('plunder_config') || {};
              const configToSave = {
                ...existingConfig,
                token: accounts[0].token,
                uid: accounts[0].uid,
                roleId: accounts[0].roleId,
                nickname: accounts[0].nickname
              };
              uni.setStorageSync('plunder_config', configToSave);
              config.value = configToSave;
              
              debugLog('已更新配置', configToSave);
            } else {
              debugLog('没有可用的账号');
              currentAccount.value = null;
              // 重置统计信息
              plunderStats.value = {
                totalAttempts: 0,
                successfulPlunders: 0,
                totalStones: 0.0,
                records: [],
                nicknameStats: {},
                beadTray: 0,
                refresh: { used: 0, total: 0 }
              };
            }
            
            // 强制更新视图
            await nextTick();
            debugLog('账号信息加载完成', { 
              currentAccount: currentAccount.value,
              stats: plunderStats.value 
            });
            return currentAccount.value;
          } catch (e) {
            console.error('加载当前账号信息失败:', e);
            debugLog('加载账号信息失败: ' + e.message);
            currentAccount.value = null;
            // 重置统计信息
            plunderStats.value = {
              totalAttempts: 0,
              successfulPlunders: 0,
              totalStones: 0.0,
              records: [],
              nicknameStats: {},
              beadTray: 0,
              refresh: { used: 0, total: 0 }
            };
            return null;
          }
        };

        // 添加定时任务相关代码
        let timeUpdateTimer = null;
        let logCleanupTimer = null;

        // 添加时间检查相关的状态变量
        const lastTimeCheck = ref(0);
        const TIME_CHECK_INTERVAL = 5000; // 5秒检查一次
        const timeCheckTimer = ref(null);
        const lastTimeCheckResult = ref(false); // 添加缓存上次检查结果

        // 修改定时任务启动函数
        const startScheduledTasks = () => {
          try {
            console.log('[定时任务] 开始启动');
            
            // 清理可能存在的旧定时器
            cleanupScheduledTasks();
            
            // 初始化时间检查状态
            lastTimeCheck.value = Date.now();
            lastTimeCheckResult.value = isWithinTimeRange();
            
            // 更新时间显示（每秒更新）
            timeUpdateTimer = setInterval(() => {
              try {
                const now = new Date();
                currentTime.value = formatTime(now);
                secondsToNextFiveMinute();
              } catch (e) {
                console.error('[定时任务] 更新时间显示失败:', e);
              }
            }, 1000);
            
            // 设置时间检查定时器（每5秒检查一次）
            timeCheckTimer.value = setInterval(() => {
              try {
                isWithinTimeRange(); // 直接调用，函数内部会处理状态更新
              } catch (e) {
                console.error('[定时任务] 时间检查失败:', e);
              }
            }, TIME_CHECK_INTERVAL);
            
            // 设置日志清理定时器
            logCleanupTimer = setInterval(() => {
              try {
                cleanupLogs();
              } catch (e) {
                console.error('[定时任务] 清理日志失败:', e);
              }
            }, LOG_CLEANUP_INTERVAL);
            
            // 保存定时器状态
            uni.setStorageSync('scheduled_tasks', {
              timeUpdateTimer: true,
              timeCheckTimer: true,
              logCleanupTimer: true,
              timestamp: Date.now()
            });
            
            console.log('[定时任务] 启动完成');
          } catch (e) {
            console.error('[定时任务] 启动失败:', e);
            // 确保清理所有定时器
            cleanupScheduledTasks();
            throw e;
          }
        };

        // 修改定时任务清理函数
        const cleanupScheduledTasks = () => {
          try {
            console.log('[定时任务] 开始清理');
            
            // 清理时间更新定时器
            if (timeUpdateTimer) {
              clearInterval(timeUpdateTimer);
              timeUpdateTimer = null;
              console.log('[定时任务] 已清理时间更新定时器');
            }
            
            // 清理时间检查定时器
            if (timeCheckTimer.value) {
              clearInterval(timeCheckTimer.value);
              timeCheckTimer.value = null;
              console.log('[定时任务] 已清理时间检查定时器');
            }
            
            // 清理日志清理定时器
            if (logCleanupTimer) {
              clearInterval(logCleanupTimer);
              logCleanupTimer = null;
              console.log('[定时任务] 已清理日志清理定时器');
            }
            
            // 清除定时器状态
            try {
              uni.removeStorageSync('scheduled_tasks');
            } catch (e) {
              console.error('[定时任务] 清除状态失败:', e);
            }
            
            console.log('[定时任务] 清理完成');
          } catch (e) {
            console.error('[定时任务] 清理失败:', e);
            // 强制清理
            timeUpdateTimer = null;
            timeCheckTimer.value = null;
            logCleanupTimer = null;
          }
        };

        // 修改 onMounted 钩子
        onMounted(async () => {
          console.log('[生命周期] 组件挂载开始');
          try {
            // 初始化 plunderStats
            plunderStats.value = {
              totalAttempts: 0,
              successfulPlunders: 0,
              totalStones: 0.0,
              records: [],
              nicknameStats: {},
              beadTray: 0,
              refresh: { used: 0, total: 0 }
            };
            
            // 加载保存的日志
            try {
              const savedLogs = uni.getStorageSync('plunder_logs');
              if (savedLogs && Array.isArray(savedLogs)) {
                logs.value = savedLogs;
                console.log('[日志] 已加载保存的日志:', logs.value.length, '条');
              }
            } catch (e) {
              console.error('[日志] 加载失败:', e);
              logs.value = [];
            }
            
            // 加载配置
            try {
              loadConfig();
              console.log('[配置] 加载完成');
            } catch (e) {
              console.error('[配置] 加载失败:', e);
              // 使用默认配置
              config.value = {
                nicknames: [],
                uid: '',
                roleId: '',
                token: '',
                threshold: '168.0',
                quickRefreshCount: '3',
                quickRefreshDuration: '40',
                quickRefreshInterval: '4',
                startTime: '10:00',
                stopTime: '11:45'
              };
            }
            
            // 加载当前账号
            try {
              const account = await loadCurrentAccount();
              console.log('[账号] 加载完成:', account?.nickname || '未登录');
              
              if (account) {
                const statsKey = `plunder_stats_${account.roleId}`;
                try {
                  const savedStats = uni.getStorageSync(statsKey);
                  if (savedStats) {
                    plunderStats.value = {
                      totalAttempts: savedStats.totalAttempts || 0,
                      successfulPlunders: savedStats.successfulPlunders || 0,
                      totalStones: savedStats.totalStones || 0.0,
                      records: savedStats.records || [],
                      nicknameStats: savedStats.nicknameStats || {},
                      beadTray: savedStats.beadTray || 0,
                      refresh: savedStats.refresh || { used: 0, total: 0 }
                    };
                    console.log('[统计] 已加载:', statsKey);
                  }
                } catch (e) {
                  console.error('[统计] 加载失败:', e);
                }
              }
            } catch (e) {
              console.error('[账号] 加载失败:', e);
              currentAccount.value = null;
            }
            
            // 启动定时任务
            try {
              startScheduledTasks();
              console.log('[定时任务] 启动完成');
            } catch (e) {
              console.error('[定时任务] 启动失败:', e);
            }
            
            console.log('[生命周期] 组件挂载完成');
          } catch (e) {
            console.error('[生命周期] 组件挂载失败:', e);
            // 确保清理所有定时器
            cleanupScheduledTasks();
          }
        });

        // 修改 onUnmounted 钩子
        onUnmounted(() => {
          cleanupScheduledTasks();
        });

        // 添加 showDebug 状态
        const showDebug = ref(false);

        // 将 onShow 移到 setup 内部
        const onShow = async () => {
          console.log('主页面显示，开始检查运行状态');
          
          // 优先检查运行状态
          try {
            const runningState = uni.getStorageSync('plunder_running');
            const manuallyStopped = uni.getStorageSync('plunder_manually_stopped') || false;
            
            console.log('主页面：存储状态检查', {
              runningState,
              manuallyStopped,
              currentState: isRunning.value
            });
            
            // 如果手动停止，强制设置为未运行状态
            if (manuallyStopped) {
              console.log('主页面：检测到手动停止状态，强制设置为未运行');
              isRunning.value = false;
              lastTimeCheckResult.value = false;
              // 确保存储状态一致
              uni.removeStorageSync('plunder_running');
              return;
            }
            
            // 检查是否在运行时间段内
            const withinTimeRange = isWithinTimeRange();
            console.log('主页面：时间检查结果', {
              withinTimeRange,
              lastCheckResult: lastTimeCheckResult.value,
              startTime: config.value.startTime,
              stopTime: config.value.stopTime,
              currentTime: new Date().toLocaleTimeString()
            });
            
            // 同步运行状态
            if (isRunning.value !== withinTimeRange) {
              console.log('主页面：同步运行状态', {
                oldState: isRunning.value,
                newState: withinTimeRange,
                storedState: runningState
              });
              isRunning.value = withinTimeRange;
              
              // 如果不在运行时间段内，确保停止运行
              if (!withinTimeRange) {
                uni.removeStorageSync('plunder_running');
                uni.$emit('running-state-changed', { isRunning: false });
                uni.$emit('globalStateChange', { isRunning: false });
              }
            }
          } catch (e) {
            console.error('检查运行状态失败:', e);
            isRunning.value = false;
            lastTimeCheckResult.value = false;
          }
          
          // 运行状态检查完成后再加载配置
          console.log('主页面：开始加载配置');
          loadConfig();
        };
        
        // 暴露 onShow 钩子
        expose({
          onShow
        });
        
        return {
          isRunning,
          status,
          countdown,
          logs,
          scrollTo,
          manuallyStopped,
          currentTime,
          info,
          config,
          plunderStats,
          currentAccount,
          isWithinTimeRange,
          startPlunder,
          stopPlunder,
          attackPrepare,
          navigateToConfig,
          navigateToAccountManager,
          clearLog,
          debugLog,
          loadCurrentAccount,
          showDebug,
          formatTime,
          formatRecordTime,
          updateStats,
          resetRunningState,
          isOperationLocked,
          acquireLock,
          releaseLock,
          normalizeNickname,
          CONSTANTS,
          startScheduledTasks,
          cleanupScheduledTasks,
        };
      },
      // 删除外部的 onShow 钩子
      // ... existing code ...
    };

</script>

<style>
.container {
  padding: 24rpx;
  padding-top: 24rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
  min-height: 100vh;
  max-width: 1200rpx;
  margin: 0 auto;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.debug-panel {
  background: #f8f9fa;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.debug-header {
  padding: 16rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  background: #e9ecef;
}

.debug-title {
  font-size: 24rpx;
  color: #495057;
}

.debug-icon {
  font-size: 24rpx;
  color: #6c757d;
}

.debug-content {
  padding: 16rpx;
  font-size: 24rpx;
  color: #495057;
  white-space: pre-wrap;
  word-break: break-all;
}

.ad-banner-container,
.ad-banner {
  display: none;
}

.control-panel {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16rpx;
  padding: 24rpx;
  margin: 0 auto 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  backdrop-filter: blur(10px);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  max-width: 1000rpx;
}

.panel-header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 0;
}

.button-group {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
  justify-content: center;
  width: 100%;
}

.control-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 100rpx;
  height: 56rpx;
  padding: 0 20rpx;
  font-size: 24rpx;
  font-weight: 500;
  border-radius: 6rpx;
  border: none;
  transition: all 0.2s ease;
  background: rgba(248, 249, 250, 0.8);
  color: #606266;
  border: 1rpx solid rgba(0, 0, 0, 0.05);
}

.control-button:hover {
  transform: translateY(-1rpx);
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.button-icon {
  margin-right: 6rpx;
  font-size: 24rpx;
}

.button-primary {
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
  border: none;
  box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.2);
}

.button-primary:hover {
  background: linear-gradient(135deg, #45a049 0%, #3d8b40 100%);
  box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.3);
}

.button-danger {
  background: linear-gradient(135deg, #f44336 0%, #e53935 100%);
  color: white;
  border: none;
  box-shadow: 0 2rpx 8rpx rgba(244, 67, 54, 0.2);
}

.button-danger:hover {
  background: linear-gradient(135deg, #e53935 0%, #d32f2f 100%);
  box-shadow: 0 4rpx 12rpx rgba(244, 67, 54, 0.3);
}

.button-secondary {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
  color: #606266;
  border: 1rpx solid rgba(220, 223, 230, 0.8);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.button-secondary:hover {
  background: linear-gradient(135deg, #e4e7eb 0%, #d4d7dc 100%);
  transform: translateY(-2rpx);
}

.status-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200rpx, 1fr));
  gap: 12rpx;
  padding: 16rpx;
  background: rgba(248, 249, 250, 0.8);
  border-radius: 8rpx;
  border: 1rpx solid rgba(0, 0, 0, 0.05);
  max-width: 1000rpx;
  margin: 0 auto;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 8rpx 12rpx;
  background: rgba(255, 255, 255, 0.5);
  border-radius: 6rpx;
  transition: all 0.2s ease;
}

.status-item:hover {
  background: rgba(255, 255, 255, 0.8);
}

.status-label {
  font-size: 22rpx;
  color: #606266;
  font-weight: 500;
}

.status-value {
  font-size: 22rpx;
  color: #1a1a1a;
  font-weight: 600;
}

.status-running {
  color: #67c23a;
}

.status-active {
  color: #67c23a;
}

.status-manual-stop {
  color: #909399;
}

.role-list {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12rpx;
  padding: 16rpx 20rpx;
  margin: 0 auto 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  height: 680rpx;
  display: flex;
  flex-direction: column;
  max-width: 1000rpx;
}

.role-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8rpx 12rpx;
  margin-bottom: 12rpx;
  background: rgba(248, 249, 250, 0.8);
  border-radius: 6rpx;
  border: 1rpx solid rgba(0, 0, 0, 0.05);
}

.role-list-title {
  font-size: 26rpx;
  font-weight: 600;
  color: #1a1a1a;
}

.role-list-count {
  font-size: 22rpx;
  color: #606266;
  background: rgba(96, 98, 102, 0.1);
  padding: 2rpx 12rpx;
  border-radius: 16rpx;
  font-weight: 500;
}

.role-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16rpx;
  overflow-y: auto;
  padding: 8rpx;
  margin: 0 -8rpx;
}

.role-card {
  background: rgba(248, 249, 250, 0.8);
  border-radius: 8rpx;
  padding: 12rpx 16rpx;
  border: 1rpx solid rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
  display: grid;
  grid-template-rows: auto 1fr;
  gap: 8rpx;
  min-height: 160rpx;
}

.role-card:hover {
  background: rgba(255, 255, 255, 0.95);
  transform: translateY(-1rpx);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.role-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12rpx;
  padding-bottom: 8rpx;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);
}

.role-nickname {
  font-size: 24rpx;
  font-weight: 600;
  color: #1a1a1a;
  flex: 1;
  min-width: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.role-stone {
  font-size: 22rpx;
  color: #909399;
  background: rgba(144, 147, 153, 0.1);
  padding: 2rpx 10rpx;
  border-radius: 16rpx;
}

.role-stone::before {
  content: '💎';
  font-size: 24rpx;
}

.role-stone.highlight {
  color: #67c23a;
  background: rgba(103, 194, 58, 0.1);
  font-weight: 600;
}

.role-stone.highlight::before {
  content: '💫';
  font-size: 24rpx;
}

.role-info {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  min-height: 0;
}

.role-level {
  font-size: 22rpx;
  color: #409eff;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.role-level::before {
  content: '⭐';
  font-size: 24rpx;
  color: #ffc107;
}

.role-detail {
  font-size: 20rpx;
  color: #606266;
  background: rgba(96, 98, 102, 0.05);
  padding: 2rpx 10rpx;
  border-radius: 4rpx;
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.role-detail::before {
  content: '📈';
  font-size: 24rpx;
}

.role-equip {
  font-size: 22rpx;
  color: #909399;
  background: rgba(144, 147, 153, 0.05);
  padding: 8rpx 12rpx;
  border-radius: 6rpx;
  border-left: 4rpx solid #909399;
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-top: 4rpx;
}

.role-equip::before {
  content: '🛡️';
  font-size: 24rpx;
}

.role-grid::-webkit-scrollbar {
  width: 6rpx;
}

.role-grid::-webkit-scrollbar-track {
  background: transparent;
}

.role-grid::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3rpx;
}

.role-grid::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

@media screen and (min-width: 768px) {
  .role-list {
    height: 720rpx;
    padding: 20rpx 24rpx;
  }

  .role-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
    padding: 12rpx;
    margin: 0 -12rpx;
  }

  .role-card {
    padding: 16rpx 20rpx;
    min-height: 180rpx;
  }

  .role-nickname {
    font-size: 26rpx;
  }

  .role-stone {
    font-size: 24rpx;
  }

  .role-level {
    font-size: 24rpx;
  }

  .role-detail, .role-equip {
    font-size: 22rpx;
  }
}

.tips {
  background: rgba(253, 246, 236, 0.9);
  border-radius: 8rpx;
  padding: 12rpx 16rpx;
  margin: 0 auto 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  border-left: 3rpx solid #e6a23c;
  box-shadow: 0 2rpx 6rpx rgba(230, 162, 60, 0.1);
  max-width: 1000rpx;
}

.tips-icon {
  font-size: 24rpx;
  color: #e6a23c;
}

.tips-content {
  flex: 1;
  font-size: 22rpx;
  color: #e6a23c;
  line-height: 1.4;
  text-align: center;
}

@media screen and (min-width: 768px) {
  .container {
    padding: 32rpx;
  }

  .control-panel {
    padding: 32rpx;
  }

  .button-group {
    gap: 20rpx;
  }

  .control-button {
    min-width: 120rpx;
    height: 60rpx;
    font-size: 26rpx;
  }

  .button-icon {
    font-size: 26rpx;
  }

  .status-info {
    grid-template-columns: repeat(4, 1fr);
    gap: 16rpx;
    padding: 20rpx;
  }

  .role-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
    padding: 12rpx;
    margin: 0 -12rpx;
  }

  .role-card {
    min-height: 180rpx;
    padding: 16rpx 20rpx;
  }

  .role-nickname {
    font-size: 26rpx;
  }

  .role-stone,
  .role-level {
    font-size: 24rpx;
  }

  .role-detail {
    font-size: 22rpx;
  }

  .tips {
    padding: 16rpx 20rpx;
  }

  .tips-icon {
    font-size: 26rpx;
  }

  .tips-content {
    font-size: 24rpx;
  }
}

::-webkit-scrollbar {
  width: 8rpx;
  height: 8rpx;
}

::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.05);
  border-radius: 4rpx;
}

::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 4rpx;
  transition: all 0.3s ease;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

.account-info-panel {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12rpx;
  padding: 16rpx 20rpx;
  margin: 0 auto 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(10px);
  border: 1rpx solid rgba(0, 0, 0, 0.05);
  max-width: 1000rpx;
  width: 100%;
}

.account-info-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16rpx;
}

.account-display {
  flex: 1;
  min-width: 0;
}

.account-nickname {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 4rpx;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.account-id {
  font-size: 22rpx;
  color: #666;
  display: block;
}

.switch-account-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8rpx 20rpx;
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
  border-radius: 6rpx;
  font-size: 24rpx;
  border: none;
  box-shadow: 0 2rpx 6rpx rgba(76, 175, 80, 0.2);
  white-space: nowrap;
  flex-shrink: 0;
  height: 48rpx;
  min-width: 120rpx;
}

.switch-account-btn:hover {
  background: linear-gradient(135deg, #45a049 0%, #3d8b40 100%);
  box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.3);
}

.button-icon {
  margin-right: 6rpx;
  font-size: 24rpx;
}

.control-panel,
.role-list,
.tips,
.log-panel,
.stats-panel,
.account-info-panel {
  width: 100%;
  max-width: 1000rpx;
  margin: 0 auto;
  box-sizing: border-box;
  position: relative;
  z-index: 2;
}

.account-info-panel.no-account {
  background: rgba(255, 255, 255, 0.8);
  border: 1px dashed #dc3545;
}

.role-card-highlight {
  border: 2px solid #28a745;
  background: rgba(40, 167, 69, 0.05);
}
</style>